<!--  -->
<template>
  <div>
    <demo></demo>
    <div class="shopping_car">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="price" label="商品信息" width="380">
          <template slot-scope="scope">
            <div class="shopping_car_pir">
              <el-image
                style="width: 100px; height: 100px"
                :src="scope.row.pir_path"
                fit="contain"
              ></el-image>
            </div>
            <div class="shopping_car_description">{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="single_price" label="单价" width="180">
        </el-table-column>
        <el-table-column label="数量" width="300">
          <template slot-scope="scope">
            <div class="shopping_car_count">
              <el-input
                @change="changeCountBtn(scope.row.count, scope.row.id)"
                v-model="scope.row.count"
                placeholder="请输入数量"
                style="width: 100px"
              ></el-input>
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="total_price" label="金额" width="180">
        </el-table-column>

        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="danger"
              icon="el-icon-delete"
              @click="deteleBtn(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <el-table
        :data="cartItem"
        style="width: 100%; font-size: 19px; color: red"
      >
        <el-table-column prop="" label="  " width="170"> </el-table-column>

        <el-table-column prop="total_price" label="总金额" width="370">
        </el-table-column>

        <el-table-column prop="total_count" label="总数量" width="390">
        </el-table-column>
        <el-table-column prop="" label=" " width="390">
          <el-button type="success" @click="buyBtn" icon="el-icon-circle-check">
            立即购买
          </el-button>
          <el-button
            type="danger"
            @click="clearBtn"
            icon="el-icon-circle-check"
          >
            清空购物车
          </el-button>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
import demo from "@/components/nav.vue";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {
    demo,
  },
  data() {
    //这里存放数据
    return {
      cartItem: [
        {
          total_price: 0,
          total_count: 0,
        },
      ],

      tableData: [],
      user_id: "",
      total_count: "",
      total_price: "",
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    changeCountBtn(count, bookId) {
      let this_ = this;
      this.$http
        .post(
          `http://localhost:88/api/book/info/update/cart/${this_.user_id}/${bookId}/${count}`
        )
        .then(function (response) {
          this_.cartItem = [];
          this_.cartItem.push({
            total_price: response.data.cart.totalPrice,
            total_count: response.data.cart.totalCount,
          });

          this_.tableData = [];
          for (var i = 0; i < response.data.books.length; i++) {
            // this_.cartItem.push('bookqqq:',response.data.books[i]);
            this_.tableData.push({
              name: response.data.books[i].name,
              pir_path: response.data.books[i].pictureHeadPath,
              id: response.data.books[i].id,
              single_price: response.data.books[i].price,
              count: response.data.books[i].count,
              total_price: response.data.books[i].totalPrice,
            });
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    },

    deteleBtn(bookId) {
      let this_ = this;
      this.$http
        .post(
          `http://localhost:88/api/book/info/delete/cart/${this.user_id}/${bookId}`
        )
        .then(function (response) {
          this_.cartItem = [];
          this_.cartItem.push({
            total_price: response.data.cart.totalPrice,
            total_count: response.data.cart.totalCount,
          });

          this_.tableData = [];
          for (var i = 0; i < response.data.books.length; i++) {
            // this_.cartItem.push('bookqqq:',response.data.books[i]);
            this_.tableData.push({
              name: response.data.books[i].name,
              pir_path: response.data.books[i].pictureHeadPath,
              id: response.data.books[i].id,
              single_price: response.data.books[i].price,
              count: response.data.books[i].count,
              total_price: response.data.books[i].totalPrice,
            });
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    },

    buyBtn() {
      let this_ = this;
      this.$http
        .post(`http://localhost:88/api/book/order/create/order/${this.user_id}`)
        .then(function (response) {
          console.log(response)

          if (response.data.code == 200) {
            this_.$message({
              showClose: true,
              message: "下单成功",
              type: "success",
            });
            this_.tableData = [];
            this_.cartItem.pop();
            this_.cartItem.push({
              total_price: 0,
              total_count: 0,
            });
          }else{
              this_.$message({
              showClose: true,
              message: response.data.msg,
              type: "error",
            });
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    },
    handleChange(v) {
      console.log(v);
    },

    clearBtn() {
      let this_ = this;
      this.$http
        .post(`http://localhost:88/api/book/info/clear/cart/${this.user_id}`)
        .then(function (response) {
          this_.cartItem.pop();
          this_.cartItem.push({
            total_price: 0,
            total_count: 0,
          });

          this_.tableData = [];
        })
        .catch(function (err) {
          console.log(err);
        });
    },

    init_user() {
      // let token = this.$store.state.token;
      // if (token == null || token.trim() == "") {
      //   this.$router.push({
      //     path: "/login",
      //   });
      //   return;
      // }
      // let this_ = this;
      // this.$http
      //   .post(`http://localhost:88/api/book/user/verify/jwt/${token}`)
      //   .then(function (response) {
      //     console.log(response);
      //     if (response.data.code == 500) {
      //       this_.$router.push({
      //         path: "/login",
      //       });
      //     } else {
      //       this_.user_id = response.data.userId;
      //       this_.getCartInfo();
      //     }
      //   })
      //   .catch(function (err) {
      //     console.log(err);
      //   });

      let this_ = this;
      this.$http
        .post(`http://localhost:88/api/book/user/verify/jwt/cookie`)
        .then(function (response) {
          console.log(response);
          if (response.data.code == 200) {
            this_.user_id = response.data.userId;
            this_.getCartInfo();
          } else {
            this_.$router.push({
              path: "/login",
            });
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    },
    getCartInfo() {
      console.log("userId:~~" + this.user_id);
      let this_ = this;
      this.$http
        .get(`http://localhost:88/api/book/info/get/cart/${this.user_id}`)
        .then(function (response) {
          console.log("cart~~~: ", response);
          this_.cartItem.pop();
          this_.cartItem.push({
            total_price: response.data.cart.totalPrice,
            total_count: response.data.cart.totalCount,
          });

          console.log("cartBooks:", response.data.cart.books);

          for (var i = 0; i < response.data.books.length; i++) {
            // this_.cartItem.push('bookqqq:',response.data.books[i]);
            this_.tableData.push({
              name: response.data.books[i].name,
              pir_path: response.data.books[i].pictureHeadPath,
              id: response.data.books[i].id,
              single_price: response.data.books[i].price,
              count: response.data.books[i].count,
              total_price: response.data.books[i].totalPrice,
            });
          }
        })
        .catch(function (err) {
          console.log(err);
        });
    },
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    this.init_user();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style scoped>
.buyBtn {
  margin-left: 1000px;
  width: 200px;
}

.shopping_car_count {
  width: 50px;
}

.shopping_car {
  width: 80%;
  margin: 0 auto;
  font-family: "Helvetica Neue";
}
.shopping_car_pir {
  width: 100px;
  height: 100px;
  float: left;
}
.shopping_car_description {
  float: left;
  margin-left: 10px;
  line-height: 100px;
}
</style>